package com.mdxq.mall.sale.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.mdxq.mall.sale.entity.CouponProductCategoryRelation;
import com.mdxq.mall.sale.entity.CouponProductRelation;
import com.mdxq.mall.sale.mapper.CouponProductCategoryRelationMapper;
import com.mdxq.mall.sale.mapper.CouponProductRelationMapper;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.mdxq.mall.sale.entity.Coupon;
import com.mdxq.mall.sale.mapper.CouponMapper;
import com.mdxq.mall.sale.service.CouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 优惠券表 服务层实现。
 *
 * @author zdy
 * @since 2025-01-12
 */
@Service
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon>  implements CouponService{
    @Autowired
    private CouponProductRelationMapper couponProductRelationMapper;
    @Autowired
    private CouponProductCategoryRelationMapper categoryRelationMapper;
    @Override
    @Transactional
    public boolean save(Coupon entity) {
        super.save(entity);
        if (CollUtil.isNotEmpty(entity.getProductRelationList())){
            for (CouponProductRelation productRelation : entity.getProductRelationList()) {
                productRelation.setCouponId(entity.getId());
                couponProductRelationMapper.insert(productRelation);
            }
        }
        if (CollUtil.isNotEmpty(entity.getProductCategoryRelationList())){
            for (CouponProductCategoryRelation categoryRelation : entity.getProductCategoryRelationList()) {
                categoryRelation.setCouponId(entity.getId());
                categoryRelationMapper.insert(categoryRelation);
            }
        }
        return true;
    }

    @Override
    public boolean updateById(Coupon entity) {
        super.updateById(entity);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("coupon_id", entity.getId());
        couponProductRelationMapper.deleteByQuery(queryWrapper);
        queryWrapper.clear();
        queryWrapper.eq("coupon_id", entity.getId());
        categoryRelationMapper.deleteByQuery(queryWrapper);
        if (CollUtil.isNotEmpty(entity.getProductRelationList())){
            for (CouponProductRelation productRelation : entity.getProductRelationList()) {
                productRelation.setCouponId(entity.getId());
                couponProductRelationMapper.insert(productRelation);
            }
        }
        if (CollUtil.isNotEmpty(entity.getProductCategoryRelationList())){
            for (CouponProductCategoryRelation categoryRelation : entity.getProductCategoryRelationList()) {
                categoryRelation.setCouponId(entity.getId());
                categoryRelationMapper.insert(categoryRelation);
            }
        }
        return true;
    }
}
